import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.util.*;

/**
 * 尝试所有可能的RSA OAEP变体来解密EP
 */
public class TryAllOAEPVariants {
    
    private static final String EP_BASE64 = "qt0AJsNLEfayUx7S15jLfmQvMOpW6JJ+jCoxeXxn676R2OiN6xpLIQWSYe8ETFUF4+AaGrVY1wMCdyUPVaHM0J+8m+q/PUFgbiP3N8xSKQc4lIzzZuckbybYiFuLbEhcblmy162S5B70UJxzB6grhIVpsG/h0uw+JPaS2yTPpPVCiN/SImdOw2g12cun6niAwRZSQktZikzzbjwkRoiO8ehrwlAFJircnT1/1zba2oaGXLc/yU6cM2vWgJdyyoXJF4Mo/5XNBTDT+8yr1hPC5MKHWcTBB/isrRTD5CczInLgXHl48KKz18GkpPM7MML1GHb4pIjfTvu8hv/SLLW0sg==";
    
    private static final String PRIVATE_KEY_BASE64 = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCz8JyumzBRR1njdxPzCFpqWXrAUBiC4ycTbTDdWdpZkciwiXU5s/OxF5i7l+Hvwc9Ggjph/PKo7PpWhxZpzyEGpd6yVN9jAjJOt23o2TesgK8L/DAMhdJL8gNxKAQumbGF+ebMbcS8jWLxvDAqpmnEW8VdCLEjF6uqOPtcDmIkBF83W6oaeu32DzTr/NS16sUGQKxlflo9qPOl7VtcIsbR52klKK4uIyY23tWCouiyG84c/Uit+PleD5EYUGEu3p7IAAG5uJNzeUd0UjZDhy6x7ue+kGgcCmCNQ4zSS/bQHMknalwqJUvUSxtIf8dq+/D78m7d4Zt9n9ZD27t4Z2jHAgMBAAECggEAAr15RVdrpvE1NzeLADpyVghCzEbr+KJI6AzTn6tMneyQZ8/QDy7kWSAI3WJ0uFf1Nhepl/BoKZZiQYsRFk9nK1i/SWvtcu6HoZc9fzw/ksrq333ZpXcsOqfW0ZRQa/0/LNEfaKGLS2vDw/afrSaXmbvkB4SoXeZwYMk5Wq+FYxL/alrNpg/lzd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+ "=".repeat(80));
        System.out.println("                尝试所有 RSA OAEP 变体解密 EP");
        System.out.println("=".repeat(80) + "\n");
        
        // 准备私钥
        PrivateKey privateKey;
        try {
            byte[] privateKeyBytes = Base64.getDecoder().decode(PRIVATE_KEY_BASE64);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            privateKey = keyFactory.generatePrivate(keySpec);
            System.out.println("✅ 私钥加载成功\n");
        } catch (Exception e) {
            System.err.println("❌ 私钥加载失败: " + e.getMessage());
            return;
        }
        
        byte[] epEncrypted = Base64.getDecoder().decode(EP_BASE64);
        System.out.println("EP加密数据长度: " + epEncrypted.length + " 字节\n");
        
        // 尝试各种算法变体
        String[] algorithms = {
            "RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING",
            "RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING",
            "RSA/ECB/OAEPPadding",
            "RSA/ECB/PKCS1Padding",
            "RSA/ECB/NoPadding"
        };
        
        System.out.println("-".repeat(80));
        for (String algorithm : algorithms) {
            System.out.println("尝试: " + algorithm);
            try {
                Cipher cipher = Cipher.getInstance(algorithm);
                cipher.init(Cipher.DECRYPT_MODE, privateKey);
                byte[] decrypted = cipher.doFinal(epEncrypted);
                
                System.out.println("  ✅ 成功！解密长度: " + decrypted.length + " 字节");
                System.out.println("  前64字节(HEX): " + bytesToHex(Arrays.copyOfRange(decrypted, 0, Math.min(64, decrypted.length))));
                
                // 如果成功，显示完整结果
                System.out.println("\n" + "=".repeat(80));
                System.out.println("🎉 找到正确的算法: " + algorithm);
                System.out.println("=".repeat(80));
                analyzeDecryptedData(decrypted);
                return; // 成功后退出
                
            } catch (Exception e) {
                System.out.println("  ❌ 失败: " + e.getMessage());
            }
            System.out.println();
        }
        
        System.out.println("-".repeat(80));
        System.out.println("\n❌ 所有算法都失败了！");
        System.out.println("\n可能的原因:");
        System.out.println("  1. 提供的私钥不是正确的私钥");
        System.out.println("  2. EP数据已被修改或损坏");
        System.out.println("  3. 需要使用libsmsdk.so中真实的私钥");
    }
    
    private static void analyzeDecryptedData(byte[] data) {
        System.out.println("\n完整数据 (HEX Dump):");
        System.out.println("-".repeat(80));
        printHexDump(data);
        
        System.out.println("\n结构分析:");
        System.out.println("-".repeat(80));
        
        if (data.length >= 32) {
            System.out.println("前32字节 (可能是AES密钥):");
            System.out.println("  " + bytesToHex(Arrays.copyOfRange(data, 0, 32)));
        }
        
        if (data.length >= 48) {
            System.out.println("字节[32:48] (可能是IV):");
            System.out.println("  " + bytesToHex(Arrays.copyOfRange(data, 32, 48)));
        }
        
        // 尝试解析为文本
        System.out.println("\n尝试解析为文本:");
        try {
            String text = new String(data, "UTF-8");
            if (text.matches("^[\\x20-\\x7E\\r\\n]*$")) {
                System.out.println("  " + text);
            } else {
                System.out.println("  (包含非打印字符)");
            }
        } catch (Exception e) {
            System.out.println("  (无法解析为文本)");
        }
    }
    
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
    
    private static void printHexDump(byte[] data) {
        for (int i = 0; i < data.length; i += 16) {
            System.out.print(String.format("%04X: ", i));
            
            for (int j = 0; j < 16; j++) {
                if (i + j < data.length) {
                    System.out.print(String.format("%02X ", data[i + j]));
                } else {
                    System.out.print("   ");
                }
                if (j == 7) System.out.print(" ");
            }
            
            System.out.print(" |");
            for (int j = 0; j < 16 && i + j < data.length; j++) {
                byte b = data[i + j];
                System.out.print((b >= 32 && b < 127) ? (char) b : '.');
            }
            System.out.println("|");
        }
    }
}



